package leetcode_100;

import helpclass.ListNode;


/**
 *@author 周杨
 *ReverseNodesInKGroup_25 给一个链表 每隔k个元素就反转
 *describe:常规
 *2018年12月24日 下午6:45:24
 */
public class ReverseNodesInKGroup_25 {
	private ListNode reverse(ListNode pre, ListNode next) {
		ListNode last = pre.next;// where first will be doomed "last"
		ListNode cur = last.next;
		while (cur != next) {
			last.next = cur.next;
			cur.next = pre.next;
			pre.next = cur;
			cur = last.next;
		}
		return last;
	}

	public ListNode reverseKGroup(ListNode head, int k) {
		if (head == null || k == 1)
			return head;

		ListNode dummy = new ListNode(0);
		dummy.next = head;
		int count = 0;
		ListNode pre = dummy;
		ListNode cur = head;
		while (cur != null) {
			count++;
			ListNode next = cur.next;
			if (count == k) {
				pre = reverse(pre, next);
				count = 0;
			}
			cur = next;
		}
		return dummy.next;
	}
}
